using System;
using System.Data;
using NHibernate;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;

namespace Webshop20.Infrastructure.Persistence.NH.UserTypes
{
    public class ObjectStoreDataUserType : IUserType
    {
        public bool Equals(object x, object y)
        {
            if (x == null)
                return false;
            return x.Equals(y);
        }

        public int GetHashCode(object x)
        {
            return x.GetHashCode();
        }

        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            return Serializer
                        .Dezerialize((byte[])NHibernateUtil.Binary.NullSafeGet(rs, names[0]));
        }

        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            NHibernateUtil.Binary.NullSafeSet(cmd, Serializer.Serialize(value), index);
        }

        public object DeepCopy(object value)
        {
            return value;
        }

        public object Replace(object original, object target, object owner)
        {
            return original;
        }

        public object Assemble(object cached, object owner)
        {
            return cached;
        }

        public object Disassemble(object value)
        {
            return value;
        }

        public SqlType[] SqlTypes
        {
            get
            {
                SqlType[] types = new SqlType[1];
                types[0] = new SqlType(DbType.Binary);
                return types;
            }
        }

        public Type ReturnedType
        {
            get { return typeof (object); }
        }

        public bool IsMutable
        {
            get { return false; }
        }
    }
}